import React from 'React';

class Bundle extends React.Component {
	constructor(props) {
		super(props);
		this.state = {
			mod: null,
		};
		this._isUnMount = false;
	}

	componentWillMount() {
		this._isUnMount = false;
		this._load(this.props);
	}
	componentWillReceiveProps(nextProps) {
		if (nextProps.load !== this.props.load) {
			this._load(nextProps);
		}
	}
	componentWillUnmount() {
		this._isUnMount = true;
	}
	_load(props) {
		this.setState({
			mod: null,
		});
		props.load(mod => {
			if (!this._isUnMount) {
				this.setState({
					mod: mod.default ? mod.default : mod,
				});
			}
		});
	}

	render() {
		return this.state.mod ? this.props.children(this.state.mod) : null;
	}
}

const Loading = () => <div>Loading...</div>;

const lazyLoad = (loadComponent) => {
	return function (props) {
		return <Bundle load={loadComponent}>{Comp => (Comp ? <Comp {...props} /> : <Loading />)}</Bundle>;
	}
};
export default lazyLoad;
